#pragma once

#include "TcpServer.hpp"
#include "HttpProtocol.hpp"

namespace HttpServerArea
{
    using namespace TcpServerArea;
    using http_handler_t = std::function<void(HttpRequest &, HttpResponse &)>;
    class HttpServer
    {
    public:
        HttpServer(int port) : _tcp_s(std::make_shared<TcpServer>(port))
        {
        }



        void Start()
        {
            // TcpServer回调 HandlerHttpRequst ,处理请求
            _tcp_s->InitTcpServer([this](sock_ptr sockptr, InetAddr client)
                                  { return this->HandlerHttpRequst(sockptr, client); });

            _tcp_s->Start();
        }

        // 处理业务的入口
        bool HandlerHttpRequst(sock_ptr sockptr, InetAddr client)
        {
            LOG(LogLevel::INFO) << "Http get a new client: " << client.NetAddr();
            std::string get_request;

            //接受客户端消息,浏览器发送
            sockptr->Recv(&get_request);
            std::cout << get_request << std::endl;

            // 处理: 请求模块
            HttpRequest req;
            req.Deserialization(get_request);
            req.Print();

            HttpResponse resp;


            // 处理: 应答模块
            std::string resp_str;
            resp.Build(req);
            resp.Serialize(&resp_str);

            //将应答完, 序列化后的字符串发送还给客户端:浏览器
            sockptr->Send(resp_str);
            return true;

        }
        ~HttpServer()
        {
        }

    private:
        std::shared_ptr<TcpServer> _tcp_s;
    };
}